﻿using System;
using System.Threading;

namespace SingletonPattern
{
    /// <summary>
    /// Auther : Jimmy.you
    /// Desc   : dobule lock singleton
    /// Date   : 2018-07-19 01:24
    /// </summary>
    public class DoubleLockSingleton
    {
        /// <summary>
        /// 线程辅助对象
        /// </summary>
        private static readonly object obj = new object();
        private static DoubleLockSingleton _instance;

        private DoubleLockSingleton() { }

        public static DoubleLockSingleton GetInstance()
        {
            // first to judge the instance is inited, if ok then return instance
            if (null == _instance)
            {
                Console.WriteLine("Current instance is not inited ? {0}", null == _instance);
                // if the instance is not inited then lock the object to avoid other thread into this code regein when curren thread accesses the code
                lock (obj)
                {
                    // print current thread hashcode & start time
                    Console.WriteLine("Current thread num is {0}, startTime is {1}", Thread.CurrentThread.GetHashCode(), DateTime.Now);
                    if (null == _instance)
                    {
                        _instance = new DoubleLockSingleton();
                    }
                    // print current thread hashcode & end time & singleton instance hashcode
                    Console.WriteLine("Current thread num is {0}, EndTime is {1}, Instance hashcode is {2}"
                        , Thread.CurrentThread.GetHashCode(), DateTime.Now, _instance.GetHashCode());
                }
            }

            return _instance;
        }
    }
}